<script setup lang="ts">
import { GridComponent, LegendComponent } from "echarts/components";
import { ReNormalCountTo } from "@/components/ReCountTo";
import { CanvasRenderer } from "echarts/renderers";
import { OrderStatsItem } from "types/order";
import { getOrderStats } from "@/api/order";
import { useDark } from "@pureadmin/utils";
import { LineChart } from "echarts/charts";
import { computed, onMounted, ref } from "vue";
import { use } from "echarts/core";
import VChart from "vue-echarts";
import dayjs from "dayjs";
import numeral from "numeral";

use([GridComponent, LegendComponent, LineChart, CanvasRenderer]);

const { isDark } = useDark();

const option = ref({
  xAxis: {
    type: "category",
    show: false,
    data: []
  },
  grid: {
    top: "12px",
    bottom: "12px",
    left: 0,
    right: 0
  },
  yAxis: {
    show: false,
    type: "value"
  },
  series: [
    {
      data: [],
      type: "line",
      symbol: "none",
      smooth: true,
      color: "#e85f33",
      lineStyle: {
        shadowOffsetY: 3,
        shadowBlur: 7,
        shadowColor: "#e85f33"
      }
    }
  ]
});

const data = ref<OrderStatsItem[]>([]);

const todayCount = ref(0);

const yesterdayCount = ref(0);

const increment = computed(() => {
  if (yesterdayCount.value === 0) {
    return "N/A";
  }
  return numeral(todayCount.value)
    .subtract(yesterdayCount.value)
    .divide(yesterdayCount.value)
    .format("+0.[00]%");
});

const renderChart = async () => {
  try {
    data.value = await getOrderStats();

    let start = dayjs().subtract(7, "day").startOf("day");
    const end = dayjs().startOf("day");

    const dataMap: Record<string, number> = {};

    while (start <= end) {
      dataMap[start.format("YYYY-MM-DD")] = 0;
      start = start.add(1, "d");
    }

    data.value.forEach(item => {
      const key = dayjs(item.created_on).format("YYYY-MM-DD");
      if (dataMap[key] !== undefined) {
        dataMap[key] += 1;
      }
    });

    const yesterday = dayjs().subtract(1, "day").startOf("day");

    yesterdayCount.value = data.value.reduce((count, item) => {
      if (dayjs(item.created_on).startOf("day").unix() === yesterday.unix()) {
        count += 1;
      }
      return count;
    }, 0);

    const today = dayjs().startOf("day");

    todayCount.value = data.value.reduce((count, item) => {
      if (dayjs(item.created_on).startOf("day").unix() === today.unix()) {
        count += 1;
      }
      return count;
    }, 0);

    option.value.xAxis.data = Object.keys(dataMap);
    option.value.series[0].data = Object.values(dataMap);
  } catch (error) {
    console.log(error);
  }
};

onMounted(() => {
  renderChart();
});
</script>
<template>
  <el-card class="line-card" shadow="never">
    <div class="flex justify-between">
      <span class="text-md font-medium"> 今日订单 </span>
      <div
        class="w-8 h-8 flex justify-center items-center rounded-md"
        :style="{
          backgroundColor: isDark ? 'transparent' : '#fff5f4'
        }"
      >
        <IconifyIconOnline icon="ep:box" color="#e85f33" width="18" />
      </div>
    </div>
    <div class="flex justify-between items-start mt-3">
      <div class="w-1/2">
        <ReNormalCountTo
          :duration="2200"
          :fontSize="'1.6em'"
          :startVal="0"
          :endVal="todayCount"
        />
        <p
          class="font-medium"
          :class="
            todayCount > yesterdayCount ? 'text-green-500' : 'text-red-500'
          "
        >
          {{ increment }}
        </p>
      </div>
      <v-chart :option="option" autoresize style="width: 100%; height: 60px" />
    </div>
  </el-card>
</template>
